﻿using System;
using System.Web.Mvc;
using HelloWorld.Code.DataAccess;
using HelloWorld.Code.Security;
using HelloWorld.Code.Util;
using HelloWorld.Models;

namespace HelloWorld.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class UsersController : Controller
    {
        [HttpGet]
        public ActionResult Index(UsersList model, int page = 1, string sort = "", string direction = "")
        {
            model.SetParameters(page, sort, direction, Request.Params);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(UsersList model, int page = 1, string sort = "", string direction = "", int hfDeleteId = 0)
        {           
            if (hfDeleteId > 0)
            {
                #region Delete

                using (var unitOfWork = new UnitOfWork())
                {
                    var repository = unitOfWork.GetUserRepository;
                    var user = repository.GetById(hfDeleteId);
                    if (user != null)
                    {
                        try
                        {
                            unitOfWork.GetUserRepository.Delete(user);
                            unitOfWork.Save();
                            ViewBag.DeleteMessage = "The user was deleted";
                            ViewBag.Deleted = true;
                        }
                        catch
                        {
                            ViewBag.DeleteMessage = "An unexpected error occured";
                            ViewBag.Deleted = false;
                        }
                    }
                    else
                    {
                        ViewBag.DeleteMessage = "The user to delete wasn't found";
                        ViewBag.Deleted = false;
                    }
                }

                #endregion

                model.SetParameters(page, sort, direction, Request.Params);
                return View(model);
            }
            
            //We do this redirect in order to preserve the search parameters in the URL after the user presses the search button.
            model.SetParameters(page, sort, direction, Request.Params);
            return RedirectToAction("Index", (new UrlHelper(ControllerContext.RequestContext)).GetRouteValueDictionaryForList(model));
        }

        [HttpGet]
        [TimeAuthorize(StartTime =  9, EndTime = 16)]
        public ActionResult Add()
        {
            ViewBag.IsNewUser = true;
            return View("User", new User {UrlReferrer = Request.UrlReferrer == null ? string.Empty : Request.UrlReferrer.AbsoluteUri});
        }

        [HttpPost]
        [TimeAuthorize(StartTime = 9, EndTime = 16)]
        public ActionResult Add(User model)
        {
            ViewBag.IsNewUser = true;
            return Save(model);
        }

        [HttpGet]
        [TimeAuthorize(StartTime = 9, EndTime = 16)]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.IsNewUser = false;
            var user = new UnitOfWork().GetUserRepository.GetById(id);
            if (user == null)
            {
                ViewBag.Error = "User not found";
                user = new User();
            }
            user.UrlReferrer = Request.UrlReferrer == null ? string.Empty : Request.UrlReferrer.AbsoluteUri;
            
            return View("User", user);
        }

        [HttpPost]
        [TimeAuthorize(StartTime = 9, EndTime = 16)]
        public ActionResult Edit(User model)
        {
            ViewBag.IsNewUser = false;
            return Save(model);
        }

        protected ActionResult Save(User model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    model.Save();
                    ViewBag.Message = "The user was saved successfully";
                }
                catch (Exception exp)
                {                    
                    ViewBag.Error = "There was an unexpected error while saving the user.";
                }
            }
            return View("User", model);
        }
    }
}
